<template>
  <div class="page-container">
    <div class="container">
    <h2>工资发放历史</h2>
    <el-table :data="salaries.records" border stripe>
      <el-table-column prop="id" label="ID" width="50" />
      <el-table-column prop="baseSalary" label="基本工资（元）" />
      <el-table-column prop="bonusSalary" label="奖金（元）" />
      <el-table-column prop="salaryDeduction" label="扣除（元）" />
      <el-table-column prop="netSalary" label="实发工资（元）" />
      <el-table-column prop="paymentDate" label="支付日期">
        <template #default="scope">
          <span>{{ formatDate(scope.row.paymentDate) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :total="salaries.total"
          @current-change="handlePageChange"
      />
    </div>
  </div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import axios from "axios";

export default {
  name: "SalariesView",
  setup() {
    const salaries = ref({
      records: [],
      total: 0,
    });
    const currentPage = ref(1);
    const pageSize = ref(10);

    // 从 sessionStorage 获取 employeeId
    const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    const employeeId = userInfo?.employeeId;

    const fetchSalaries = async (page = 1) => {
      try {
        const response = await axios.get("http://localhost:8080/employee/getSalaries", {
          params: {
            employeeId, // 从 sessionStorage 获取的 employeeId
            page: page,
            size: pageSize.value,
          },
        });
        if (response.data.code === 200) {
          salaries.value = response.data.data;
        } else {
          console.error("获取数据失败：", response.data.message);
        }
      } catch (error) {
        console.error("请求失败：", error);
      }
    };

    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchSalaries(page);
    };

    // 日期格式化
    const formatDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份补零
      const day = String(d.getDate()).padStart(2, '0'); // 日期补零

      return `${year}年${month}月${day}日`;
    };


    onMounted(() => {
      fetchSalaries();
    });

    return {
      salaries,
      currentPage,
      pageSize,
      handlePageChange,
      formatDate,
    };
  },
};
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.container {
   padding: 20px;
   max-width: 1200px;
   margin: 0 auto;
   background-color: #fff;
   border-radius: 10px;
   box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
 }
</style>
